package db

import (
	"aqielife.cn/spider/config"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
)

var (
	DB *gorm.DB
)

func InitDB() {
	var err error
	setting, _ := config.ReadSetting()
	aqie := setting.DbInfo
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local&timeout=%s", aqie.User, aqie.Pwd, aqie.Host, aqie.Port, aqie.Db, aqie.Timeout)

	// gorm.Config 参考 https://gorm.io/docs/gorm_config.html
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "sp_",
			SingularTable: true,
		},
		Logger: logger.Default.LogMode(logger.Silent),
	})
	if err != nil {
		panic("连接数据库失败, error=" + err.Error())
	} else {
		log.Println("数据库连接成功")
	}
}
